package com.example.miaosh.controller;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.miaosh.code.SystemConstant;
import com.example.miaosh.entity.UserInfo;
import com.example.miaosh.entity.UserPass;
import com.example.miaosh.service.UserInfoService;
import com.example.miaosh.service.UserPassService;
import com.example.miaosh.util.EncryptKit;
import com.example.miaosh.util.JwtUtils;
import com.example.miaosh.util.ResultUnify;
import com.example.miaosh.util.StringUtil;

/**
 * 用户控制器
 * 
 * @author kai
 *
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserInfoService userInfoService;

	@Autowired
	private UserPassService userPassService;

	@Autowired
	private HttpServletRequest httpServletRequest;

	// 用户获取otp短信接口
	@RequestMapping("/getotp")
	public ResultUnify getOtp(String telphone) {

		ResultUnify result = new ResultUnify();
		if (StringUtil.isEmpty(telphone)) {
			return result.custom(null, 415, "缺少必传参数...");
		}
		// 需要按照一定的规则生成OTP验证码
		Random random = new Random();
		int randomInt = random.nextInt(99999);
		randomInt += 10000;
		String otpCode = String.valueOf(randomInt);

		// 将OTP验证码同对应用户的手机号关联,使用httpsession的方式绑定他的手机号与OTPCode
		httpServletRequest.getSession().setAttribute(telphone, otpCode);
		// 将OTP验证码通过短信通道发信给用户（省略）
		System.out.println("telephone=" + telphone + "   otpCode=" + otpCode);
		return result.success();
	}

	// 用户注册接口
	@RequestMapping("/register")
	public ResultUnify registerMessage(String telphone, String otpCode, int age, String name, String password,
			String gender, String registerMore, String thirdPartyId) throws NoSuchAlgorithmException {

		ResultUnify result = new ResultUnify();
		if (StringUtil.isEmpty(telphone, otpCode, name, age, password)) {
			return result.custom(null, 415, "缺少必传参数...");
		}
		// 验证手机号和对应的otpcode相符合
		String inSessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute(telphone);// 从之前的httpsession中获取存放的电话和otpcode
		System.out.println(inSessionOtpCode);
		if (!otpCode.equals(inSessionOtpCode)) {
			return result.custom(null, 415, "短信验证码错误...");
		}
		Map<String, Object> map = new HashMap<>();
		map.put("telphone", telphone);
		long countMap = userInfoService.getByMapTotal(map);
		// 判断该手机号是否注册过
		if (countMap >= 1) {
			return result.custom(null, 400, "该手机已注册...");
		}

		// 判断该账号是否注册过

		// 用户注册流程
		UserInfo userMesg = new UserInfo();
		userMesg.setAge(age);
		userMesg.setGender(gender);
		userMesg.setName(name);
		userMesg.setTelphone(telphone);
		userMesg.setRegisterMore("byTelpone");
		int countM = userInfoService.save(userMesg);

		System.out.println(userMesg.getId() + "--------------------------------");
		UserPass pass = new UserPass();
		pass.setPassword(EncryptKit.Base64.encode(password.getBytes()));
		System.out.println("解密的内容：" + EncryptKit.Base64.decodeToStr(pass.getPassword(), "UTf-8"));
		pass.setUserId(userMesg.getId());
		int countp = userPassService.save(pass);
		if (countp < 1 || countM < 1) {
			return result.custom(null, 400, "注册成失败...");
		}
		return result.custom(null, 200, "注册成功...");
	}

	/**
	 * 用户登录
	 * 
	 * @param telphone
	 * @param password
	 * @return
	 */
	@RequestMapping("/login")
	public ResultUnify login(String telphone, String password) {
		ResultUnify result = new ResultUnify();
		if (StringUtil.isEmpty(telphone, password)) {
			return result.custom(null, 415, "缺少毕传参数");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("telphone", telphone);
		UserInfo userInfo = userInfoService.getRecord(map);
		if (userInfo != null) {
			UserPass userPassInfo = new UserPass();
			userPassInfo.setUserId(userInfo.getId());
			UserPass resultUserPassInfo = userPassService.listByParameter(userPassInfo);
			if (resultUserPassInfo != null) {
				// 把获取的密码解密，在于输入的密码做对比
				if (EncryptKit.Base64.decodeToStr(resultUserPassInfo.getPassword(), "UTF-8").equals(password)) {
					// 把token返回给客户端-->客户端保存至cookie-->客户端每次请求附带cookie参数
					String JWT = JwtUtils.createJWT("1", telphone, SystemConstant.JWT_TTL);
					return result.success(JWT);
				}
			} else {
				return result.custom(null, 500, "用户名或密码错误...");
			}
		}
		return result.custom(null, 500, "用户名或密码错误...");
	}

	@RequestMapping("/get")
	public ResultUnify selectId(Integer id) {

		ResultUnify result = new ResultUnify();
		if (StringUtil.isEmpty(id)) {
			return result.custom(null, 415, "缺少必传参数..");
		}
		UserInfo userInfo = userInfoService.findById(id);
		System.out.println(userInfo + "*********************");
		if (userInfo == null) {
			return result.custom(null, 400, "没有此记录..");
		}
		return result.success(userInfo);
	}

	/**
	 * 加密登录（加密登录测试）
	 */
	@RequestMapping("/login1")
	public ResultUnify login1(String telphone, String password) {
		ResultUnify result = new ResultUnify();
		if (StringUtil.isEmpty(telphone, password)) {
			return result.custom(null, 415, "缺少毕传参数");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("telphone", telphone);
		UserInfo userInfo = userInfoService.getRecord(map);
		if (userInfo != null) {
			UserPass userPassInfo = new UserPass();
			userPassInfo.setUserId(userInfo.getId());
			UserPass resultUserPassInfo = userPassService.listByParameter(userPassInfo);
			if (resultUserPassInfo != null) {
				// 把获取的密码解密，在于输入的密码做对比
				if (EncryptKit.Base64.decodeToStr(resultUserPassInfo.getPassword(), "UTF-8").equals(password)) {
					// 把token返回给客户端-->客户端保存至cookie-->客户端每次请求附带cookie参数
					String JWT = JwtUtils.createJWT("1", telphone, SystemConstant.JWT_TTL);
					return result.success(JWT);
				}
			} else {
				return result.custom(null, 500, "用户名或密码错误...");
			}
		}
		return result.custom(null, 500, "用户名或密码错误...");

	}
}
